package com.example.shoppingmallspringboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;


/**
 * 静态文件映射
 * */

@Configuration
public class StaticFileConfig implements WebMvcConfigurer {
//StaticFileConfig 的作用是设置静态资源的存储位置和访问方式，以及配置跨域请求的处理策略，以便于前端应用能够正常访问后端服务提供的静态资源

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        File imagesDir = new File(System.getProperty("user.dir") + "/files/images/");
        if (!imagesDir.exists()) {
            imagesDir.mkdirs();
        }

        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:" + System.getProperty("user.dir") + "/files/images/" );
    }


    // 为了上述@Value能生效，因为@Configuration先执行，此时@value为null
    // 所以先加载@value相关的
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }
}
